package com.suke.czx.modules.customer.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.suke.czx.common.annotation.SysLog;
import com.suke.czx.common.base.AbstractController;
import com.suke.czx.common.utils.*;
import com.suke.czx.common.validate.CustomerSaveGroup;
import com.suke.czx.common.validate.CustomerUpdateGroup;
import com.suke.czx.modules.customer.entity.Customer;
import com.suke.czx.modules.customer.service.CustomerService;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * 应用模块名称: 客户
 * 代码描述: 客户控制层
 * copyright: AUZAR ALL RIGHTS RESERVED
 * company: AUZAR
 *
 * @author: 颜米晨
 * @date: 2021/08/31 10:16:16
 */
@Validated
@RestController
@RequestMapping("/api/customer")
@AllArgsConstructor
@Api(value = "CustomerController", tags = "客户管理")
public class CustomerController extends AbstractController {

    private final CustomerService customerService;

    /**
     * 分页查询客户列表
     * @param params 查询参数
     * @return VO
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:customer:list')")
    public R list(@RequestParam Map<String, Object> params) {
        if (StrUtil.isBlankIfStr(params.get(FieldConstant.PAGE)) || StrUtil.isBlankIfStr(FieldConstant.LIMIT)) {
            return R.error("缺少分页信息");
        }
        // 查询列表数据
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(FieldConstant.DEL_FLG, CodeConstant.NOT_DEL);
        if (params.size() > 2){
            queryWrapper.eq(!StrUtil.isBlankIfStr(params.get(FieldConstant.CUSTOMER_GRADE)), StrUtil.toUnderlineCase(FieldConstant.CUSTOMER_GRADE), params.get(FieldConstant.CUSTOMER_GRADE))
                    .like(!StrUtil.isBlankIfStr(params.get(FieldConstant.COMPANY_NAME)), StrUtil.toUnderlineCase(FieldConstant.COMPANY_NAME), params.get(FieldConstant.COMPANY_NAME))
            .like(!StrUtil.isBlankIfStr(params.get(FieldConstant.BUSINESS_SCOPE)), StrUtil.toUnderlineCase(FieldConstant.BUSINESS_SCOPE), params.get(FieldConstant.BUSINESS_SCOPE));
        }
        IPage<Customer> customerPage = customerService.page(mpPageConvert.pageParamConvert(params), queryWrapper);
        return Objects.requireNonNull(R.ok().put(FieldConstant.TOTAL, customerPage.getTotal())).setData(Optional.ofNullable(customerPage.getRecords()).orElse(Lists.newArrayList()));
    }

    /**
     * 查询所有客户
     * @return VO
     */
    @RequestMapping(value = "/select", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:customer:select')")
    public R select() {
        // 查询所有数据
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(FieldConstant.DEL_FLG, CodeConstant.NOT_DEL);
        return R.ok().setData(Optional.ofNullable(customerService.list(queryWrapper)).orElse(Lists.newArrayList()));
    }

    /**
     * 获取客户详情
     * @param customerId 客户id
     * @return VO
     */
    @RequestMapping(value = "/info/{customerId}", method = RequestMethod.GET)
    @PreAuthorize("hasRole('but:customer:info')")
    public R info(@PathVariable("customerId") Long customerId) {
        Customer customer = customerService.getById(customerId);
        return R.ok().setData(customer);
    }

    /**
     * 保存客户
     * @param customer 客户
     * @param bindingResult bindingResult
     * @return VO
     */
    @SysLog("保存客户")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:customer:save')")
    public R save(@Validated(CustomerSaveGroup.class) Customer customer, BindingResult bindingResult) {
        // 入参校验结果
        if (bindingResult.hasErrors()) {
            return R.error(ParamValidateUtil.paramVilated(bindingResult));
        }
        // 校验客户名称是否存在
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StrUtil.toUnderlineCase(FieldConstant.COMPANY_NAME), customer.getCompanyName());
        if (ListUtil.size(customerService.list(queryWrapper)) != 0) {
            return R.error("客户名称已存在");
        }
        customer.setCreator(getUserId());
        customer.setCreateTime(new Date());
        customerService.save(customer);
        return R.ok();
    }

    /**
     * 更新客户
     * @param customer 联系人
     * @param bindingResult bindingResult
     * @return VO
     */
    @SysLog("更新客户")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:customer:update')")
    public R update(@Validated(CustomerUpdateGroup.class) Customer customer, BindingResult bindingResult) {
        // 入参校验结果
        if (bindingResult.hasErrors()) {
            return R.error(ParamValidateUtil.paramVilated(bindingResult));
        }
        customer.setUpdater(getUserId());
        customer.setUpdateTime(new Date());
        customerService.updateById(customer);
        return R.ok();
    }

    /**
     * 删除客户
     * @param customerId 客户编码
     * @return VO
     */
    @SysLog("删除客户")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @PreAuthorize("hasRole('but:customer:delete')")
    public R delete(@NotNull(message = "客户编码不能为空") Long customerId) {
        return customerService.updateDelCustomer(customerId, getUserId());
    }

}
